<?php

/**
 * controller Class
 *
 * Class for controlling the interaction between model and views
 * 
 * The controller is receives the requests action from the browser,
 * calls to the apropiate model and renders a view.
 * 
 * The arguments are passed via the request parameters
 *
 * @author Victor Nava
 * @author Eduardo Nava
 */
class controller{
	public $model;
	public $request;

	function __construct(){
	}

	/**
	 * Pagination helpler
	 * Returns the proper link for the next and prev page
	 *
	 * @param $page
	 * @return unknown_type
	 */
	function getPrevNextPage($page){
		$args=split("&", $_SERVER['QUERY_STRING']);
		$args1=array();
		$count=0;

		if(!empty($args[0])){
			foreach ($args as $arg){
				$keyValue = split("=", $arg);
				$key=$keyValue[0];
				$value=$keyValue[1];
				if ($key == "page" && $page=='next'){
					$value = (int)$value +1;
					$count++;
				}elseif ($key == "page" && $page=='prev' && (int)$value>0){
					$value= (int)$value -1;
					$count++;
				}
				if($key!=null || $value!=null){
					$keyValue="$key=$value";
					$args1[]=$keyValue;
				}
			}
		}
		if ($count<=0){
			if ($page=='next'){
				return "router.php?".(!empty($args1) ? implode('&', $args1):"")."&page=1";
			}else{
				return "router.php?".(!empty($args1) ? implode('&', $args1):"")."&page=0";
			}
		}
		return "router.php?".implode("&", $args1);
	}
	
	/**
	 * Checks if the user in the session is logged in
	 * When the user is not logged in causes a redirection to the previous page
	 * @return void
	 */
	function requireLogin(){
		if(!isset($_SESSION['user'])){
			$_SESSION['flash'] = "You need to be logged in to do that. Please log in or Register.";
			$page = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : HOME_PAGE;
			redirect($page);
		}
	}

	/**
	 * Set the flash message to be retrieved by the html flash function
	 * 
	 * @param $message
	 * @return void
	 */
	function setFlash($message){
		$_SESSION['flash'] = $message;
	}

	/**
	 * Get the flash message from the sesion
	 * 
	 * @param $message
	 * @return String flass message
	 */
	function getFlash(){
		return $_SESSION['flash'];
	}
}
?>
